﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Guoc.BigMall.Infrastructure.Payment
{
   public class AbstractRequest
    {
        private SortedDictionary<string, object> _content = new SortedDictionary<string, object>();

        public void Add(string key, object value)
        {
            if (!_content.ContainsKey(key))
            {
                _content.Add(key, value);
            }
        }

        public void AddRange(SortedDictionary<string, object> items)
        {
            foreach (var item in items)
            {
                Add(item.Key, item.Value);
            }
        }

        public T GetValue<T>(string key)
        {
            if (_content.ContainsKey(key))
            {
                return (T)_content[key];
            }
            else
            {
                return default(T);
            }
        }

        public object GetValue(string key)
        {
            if (_content.ContainsKey(key))
            {
                return _content[key];
            }
            else {
                return null;
            }
        }

        public SortedDictionary<string, object> Content
        {
            get
            {
                return _content;
            }
        }

        /// <summary>
        ///  检查必填key
        /// </summary>
        /// <param name="key"></param>
        public void CheckRequired(string key)
        {
            object value = null;
            _content.TryGetValue(key, out value);
            if (value == null) {
                throw new FriendlyException(string.Format("支付参数{0}必填",key));
            }
        }


        /**
         * @Dictionary格式转化成url参数格式
         * @ return url格式串, 该串不包含sign字段值
         */
        public string ToUrl()
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in _content)
            {
                if (pair.Value == null)
                {
                    throw new Exception("Data内部含有值为null的字段!");
                }

                if (pair.Key != "sign" && pair.Value.ToString() != "")
                {
                    buff += pair.Key + "=" + pair.Value + "&";
                }
            }
            buff = buff.Trim('&');
            return buff;
        }

        public const string SIGN_TYPE_MD5 = "MD5";
        public const string SIGN_TYPE_HMAC_SHA256 = "HMAC-SHA256";
        public const string SIGN_TYPE_SHA1 = "SHA1";

        /// <summary>
        /// 生成签名，详见签名生成算法
        /// </summary>
        /// <param name="signType">签名类型</param>
        /// <param name="mchKey">商户密匙</param>
        /// <returns></returns>
        public string MakeSign(string signType, string mchKey)
        {
            //转url格式
            string str = ToUrl();
            //在string后加入API KEY
            str += "&key=" + mchKey;
            if (signType == SIGN_TYPE_MD5)
            {
                var md5 = MD5.Create();
                var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                var sb = new StringBuilder();
                foreach (byte b in bs)
                {
                    sb.Append(b.ToString("x2"));
                }
                //所有字符转为大写
                return sb.ToString().ToUpper();
            }
            else if (signType == SIGN_TYPE_HMAC_SHA256)
            {
                return CalcHMACSHA256Hash(str, mchKey);
            }
            else
            {
                throw new FriendlyException("sign_type 不合法");
            }
        }

        /// <summary>
        ///  生成js 签名
        /// </summary>
        /// <param name="signType"></param>
        /// <returns></returns>
        public string MakeJsSign(string signType)
        {
            //转url格式
            string str = ToUrl();
            //在string后加入API KEY
          //  str += "&key=" + mchKey;
            if (signType == SIGN_TYPE_MD5)
            {
                var md5 = MD5.Create();
                var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                var sb = new StringBuilder();
                foreach (byte b in bs)
                {
                    sb.Append(b.ToString("x2"));
                }
                //所有字符转为大写
                return sb.ToString().ToUpper();
            }
            else if (signType == SIGN_TYPE_SHA1)
            {
                return Sha1(str);
            }
            else
            {
                throw new FriendlyException("sign_type 不合法");
            }
        }

        /// <summary>
        /// 基于Sha1的自定义加密字符串方法：输入一个字符串，返回一个由40个字符组成的十六进制的哈希散列（字符串）。
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <returns>加密后的十六进制的哈希散列（字符串）</returns>
        public string Sha1(string str)
        {
            var buffer = Encoding.UTF8.GetBytes(str);
            var data = SHA1.Create().ComputeHash(buffer);

            var sb = new StringBuilder();
            foreach (var t in data)
            {
                sb.Append(t.ToString("x2"));
            }

            return sb.ToString();
        }

        private string CalcHMACSHA256Hash(string plaintext, string salt)
        {
            string result = "";
            var enc = Encoding.Default;
            byte[]
            baText2BeHashed = enc.GetBytes(plaintext),
            baSalt = enc.GetBytes(salt);
            System.Security.Cryptography.HMACSHA256 hasher = new HMACSHA256(baSalt);
            byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
            result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
            result= result.ToUpper();
            return result;
        }

        public string ToXml()
        {
            //数据为空时不能转化为xml格式
            if (0 == _content.Count)
            {
                throw new Exception("数据为空!");
            }

            string xml = "<xml>";
            foreach (KeyValuePair<string, object> pair in _content)
            {
                //字段值不能为null，会影响后续流程
                if (pair.Value == null)
                {
                    // Log.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!");
                    throw new Exception("data内部含有值为null的字段!");
                }
                if (pair.Value.GetType() == typeof(int))
                {
                    xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
                }
                else if (pair.Value.GetType() == typeof(string))
                {
                    xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
                }
                else//除了string和int类型不能含有其他数据类型
                {
                    //  Log.Error(this.GetType().ToString(), "WxPayData字段数据类型错误!");
                    throw new Exception("Data字段数据类型错误!");
                }
            }
            xml += "</xml>";
            return xml;
        }

        /**
      * @将xml转为WxPayData对象并返回对象内部的数据
      * @param string 待转换的xml串
      * @return 经转换得到的Dictionary
      * @throws WxPayException
      */
        public SortedDictionary<string, object> FromXml(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                // Log.Error(this.GetType().ToString(), "将空的xml串转换为WxPayData不合法!");
                throw new Exception("将空的xml串转换为Data不合法!");
            }


            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = null;
            xmlDoc.LoadXml(xml);
            XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
            XmlNodeList nodes = xmlNode.ChildNodes;
            foreach (XmlNode xn in nodes)
            {
                XmlElement xe = (XmlElement)xn;
                this._content[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
            }

            //if (this._content["return_code"].ToString() == "SUCCESS" && this._content["result_code"].ToString() == "SUCCESS")
            //{
            //    return Content;
            //}
            //else
            //{
            //    var errMsg = this._content["return_msg"].ToString();
            //    throw new Exception("err:" + errMsg);
            //}
            return this._content;
        }

        /**
        * 
        * 检测签名是否正确
        * 正确返回true，错误抛异常
        */
        public bool CheckSign(string signType, string mchkey)
        {
            //如果没有设置签名，则跳过检测
            CheckRequired("sign");
            //如果设置了签名但是签名为空，则抛异常
            if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                // Log.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!");
                throw new Exception("WxPayData签名存在但不合法!");
            }

            //获取接收到的签名
            string return_sign = GetValue("sign").ToString();

            //在本地计算新的签名
            string cal_sign = MakeSign(signType, mchkey);

            if (cal_sign == return_sign)
            {
                return true;
            }

            //  Log.Error(this.GetType().ToString(), "WxPayData签名验证错误!");
            throw new Exception("WxPayData签名验证错误!");
        }


        public  string GenerateNonceStr()
        {
            return Guid.NewGuid().ToString().Replace("-", "").ToLower();
        }

        public string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
    }
}
